'use strict';
'require view';
'require fs';
'require rpc';
'require validation';
'require ui';
var callDevsDump = rpc.declare({
	object: 'sihan.energy',
	method: 'read_devs',
	expect: {}
});

function getDevs() {
	return L.resolveDefault(callDevsDump(), {})
		.then(function(res) {
			console.log(res);
			return res.result;
		});
}
/**
 * 格式化时间戳为可读字符串
 * @param {number} timestamp - 时间戳（毫秒）
 * @param {string} [format='YYYY-MM-DD HH:mm:ss'] - 格式字符串
 * @returns {string} 格式化后的时间字符串
 */
function timestampToDateFormat(timestamp) {
  let date = new Date(timestamp*1000);
  let formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
  return formattedDate;
}
function isMoreThan5Minutes(timestamp) {
    const currentTimestamp = Date.now(); // 获取当前时间戳（毫秒）
    const difference = currentTimestamp - timestamp * 1000; // 计算时间差（毫秒）
    const fiveMinutesInMs = (5 * 60 + 10) * 1000; // 5分钟的毫秒数
    return difference > fiveMinutesInMs;
}
return view.extend({
	load: function() {
		return getDevs();
	},
	buttonClick: function(){},
	render: function(data) {
		
		var table = E('table', {
			'class': 'table',
		}, [
			E('tr', {'class': 'tr table-titles'}, 
			[
				E('th', {'class': 'th nowrap'}, _('设备编号')), 
				E('th', {'class': 'th'}, _('电源工作状态')), 
				E('th', {'class': 'th hide-xs'}, _('电池电压')), 
				E('th', {'class': 'th'}, _('电池电流')), 
				E('th', {'class': 'th'}, _('电池电量')), 
				//E('th', {'class': 'th'}, _('电池状态')), 
				E('th', {'class': 'th'}, _('负载电压')), 
				E('th', {'class': 'th'}, _('负载功率')), 
				E('th', {'class': 'th'}, _('阵列电压')), 
				E('th', {'class': 'th'}, _('上传时间')), 
				/*
				E('th', {'class': 'th'}, _('低压次数')), 
				E('th', {'class': 'th'}, _('今日放电量')), 
				E('th', {'class': 'th'}, _('昨日放电量')), 
				E('th', {'class': 'th'}, _('今日充电量')), 
				E('th', {'class': 'th'}, _('昨日放电量')), 
				E('th', {'class': 'th'},  _('电源开关'))
				*/
			])
		]);
		cbi_update_table(table, [], E('em', {
			'class': 'spinning'
		}, _('Collecting data...')))
		
		cbi_update_table(table, data.map(L.bind(function(device) {
			console.log(device);
			var rows = [device.sn, 
				isMoreThan5Minutes(device.seconds) ? "<span style='color:red'>离线</span>" : (device.powerStatus == 1 ? "<span style='color:green'>工作中</span>":"<span style='color:yellow'>休眠中</span>"), 
				device.batteryVoltage, device.batteryElectric, device.batteryCapacity, device.loadVoltage, device.loadPower, device.columnVoltage, timestampToDateFormat(device.seconds)];
			rows.push(E('button',{
				'class': 'cbi-button cbi-button-apply',
				'click': L.bind(this.buttonClick, this, null)
			},[_('打开电源')]))
			return rows;
		}, this)), E('em', _('没有数据')));
		
		
		return E([E('h3', _('Associated Stations')), table]);
	},
	handleSaveApply: null,
	handleSave: null,
	handleReset: null
});